package com.cjj.gen.modular.controller;

import com.cjj.gen.action.config.WebGeneratorConfig;
import com.cjj.gen.action.model.GenQo;
import com.cjj.gen.modular.factory.DefaultTemplateFactory;
import com.cjj.gen.modular.service.ITableService;
import com.cjj.gen.modular.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Proxy;

/**
 * 代码生成控制器
 *
 * @author fengshuonan
 * @Date 2017年11月30日16:39:19
 */
@Controller
@RequestMapping("/code")
public class CodeController {

    private static String PREFIX = "/code";

    @Autowired
    private TableService tableService;

    private final String url = "jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false";

    private final String username = "root";

    private final String password = "123456";

    /**
     * 跳转到代码生成主页
     */
    @RequestMapping("")
    public String blackboard(Model model) {
        model.addAttribute("tables", tableService.getAllTables());
        model.addAttribute("params", DefaultTemplateFactory.getDefaultParams());
        model.addAttribute("templates", DefaultTemplateFactory.getDefaultTemplates());
        return PREFIX + "/code.html";
    }

    /**
     * 生成代码
     */
    @RequestMapping(value = "/generate", method = RequestMethod.POST)
    @ResponseBody
    public Object generate(GenQo genQo) {
        genQo.setUrl(url);
        genQo.setUserName(username);
        genQo.setPassword(password);
        WebGeneratorConfig webGeneratorConfig = new WebGeneratorConfig(genQo);
        webGeneratorConfig.doMpGeneration();
        webGeneratorConfig.doGunsGeneration();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    public static void main(String[] args) {
        ITableService tableService = new TableService();
        Class<? extends ITableService> aClass = tableService.getClass();
        ITableService proxy1 = (ITableService) Proxy.newProxyInstance(TableService.class.getClassLoader(), aClass.getInterfaces(), (proxy, method, args1) -> {
            System.out.println("proxy");
            method.invoke(tableService, args1);
            return null;
        });
        proxy1.test();

    }

}
